#include "mainwindow.h"
#include "./ui_mainwindow.h"
#include <QDebug>
#include <QMenu>
#include <QAction>
#include <QString>
#include <QIcon>
#include <QMouseEvent>
#include <QLayout>
#include <QLabel>
#include <QPushButton>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QTimer>
#include <QDateTime>
#include <QPixmap>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QMessageBox>
#include "setdialog.h"
#include <QJsonDocument>
#include <QJsonObject>
#include <QFile>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    InitAll();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::InitAll()
{
    menuIsVisible=false;
    isShowIcon=true;
    InitUI();
    InitSet();
    //设置窗口
    qDebug()<<this->width()<<" "<<this->height();
    this->setFixedSize(widthUI,heightUI);
    //setFixedSize(100,100);
    this->setWindowFlags(Qt::WindowStaysOnTopHint|Qt::FramelessWindowHint);

    //设置右键菜单
    InitRigtUI();
    // 天气
    InitWeahter();
    // 定时显示
    QTimer *timer=new QTimer(this);
    connect(timer,&QTimer::timeout,this,&MainWindow::updateTime);
    timer->start(500);
    updateTime();

    connect(menu,&QMenu::aboutToShow,this,[=](){menuIsVisible=true;});
    connect(menu,&QMenu::aboutToHide,this,[=](){
        menuIsVisible=false;
        this->setWindowOpacity(opacityHide);
    });
}

void MainWindow::InitSet()
{
    //初始化数据
    isShowIcon=true;
    isShow12H=false;
    isShowS=false;
    isShowDate=true;
    opacityShow=1.0;
    opacityHide=0.7;
}

void MainWindow::InitUI()
{
    this->setWindowTitle("Assistant");
    this->setWindowIcon(QIcon(":/res/icon/A.png"));
    // 创建中心部件并设置为主窗口的中心部件
    QWidget *centralWidget = new QWidget(this);
    this->setCentralWidget(centralWidget);

    // 创建垂直布局，并设置到中心部件
    mainLayout = new QVBoxLayout(centralWidget);
    mainLayout->setSpacing(0);

    // 创建标签，并指定父对象为中心部件
    if(isShowIcon){
        labelIcon=new QLabel(centralWidget);
        labelIcon->setPixmap(QPixmap(":/res/icon/A.png"));
        labelIcon->setFixedSize(50,50);
        labelIcon->setAlignment(Qt::AlignLeft);
        labelIcon->setScaledContents(true);
    }

    labelTime = new QLabel(centralWidget);
    labelTime->setText("时间");
    labelTime->setAlignment(Qt::AlignCenter);
    labelTime->setStyleSheet("font-size: 100px; font-weight: bold;");
    // 日期
    hBoxLayout=new QHBoxLayout(centralWidget);
    labelDate = new QLabel(centralWidget);
    labelDate->setText("日期");
    labelDate->setAlignment(Qt::AlignCenter);
    labelDate->setStyleSheet("font-size: 20px;");
    // 天气
    labelWeather= new QLabel(centralWidget);
    labelWeather->setText("加载天气中");
    labelWeather->setAlignment(Qt::AlignCenter);
    labelWeather->setStyleSheet("font-size: 20px;");
    hBoxLayout->addWidget(labelDate);
    hBoxLayout->addWidget(labelWeather);

    // 按顺序添加控件：时间标签 → 弹性空间 → (日期标签+天气)
    // mainLayout->addWidget(labelIcon);
    mainLayout->addWidget(labelTime);
    mainLayout->addStretch(1);  // 添加弹性空间占据中间区域
    mainLayout->addLayout(hBoxLayout);
}

void MainWindow::InitRigtUI()
{
    menu=new QMenu(this);

    //设置最小化
    actShowMinSize=new QAction(QIcon(":/res/icon/minSize.png"),tr("最小化"));
    menu->addAction(actShowMinSize);
    connect(actShowMinSize,&QAction::triggered,this,&MainWindow::showMinimized);
    //设置
    actSet=new QAction(QIcon(":/res/icon/set.png"),tr("设置"));
    menu->addAction(actSet);
    connect(actSet,&QAction::triggered,this,&MainWindow::do_actSet_triggered);

    //设置退出
    actClose=new QAction(QIcon(":/res/icon/close.png"),tr("退出"));
    menu->addAction(actClose);
    connect(actClose,&QAction::triggered,this,&MainWindow::close);
}

void MainWindow::InitWeahter()
{
    manager=new QNetworkAccessManager(this);
    connect(manager,&QNetworkAccessManager::finished,[](){
        qDebug()<<"manager finish!=====";
    });
    QNetworkRequest res(apiWeather);
    reply=manager->get(res);
    //QNetworkRequest网络请求后进行数据读取
    connect(manager,&QNetworkAccessManager::finished,this,&MainWindow::readHttpReply);
}

void MainWindow::updateTime()
{
    int w=widthUI,h=heightUI;
    QDateTime dateTime=QDateTime::currentDateTime();
    //图标显示
    if(isShowIcon){
        labelIcon->show();
    }else{
        labelIcon->hide();
    }

    //时钟显示
    QString str="";
    if(isShow12H){
        if(isShowS){
            str=dateTime.toString("hh:mm:ss AP");
            w+=100;
        }else{
            str=dateTime.toString("hh:mm AP");
        }
        w+=80;
    }else{
        if(isShowS){
            str=dateTime.toString("HH:mm:ss");
            w+=100;
        }else{
            str=dateTime.toString("HH:mm");
        }
    }
    labelTime->setText(str);

    //日期显示
    if(isShowDate){
        labelDate->setText(dateTime.toString("yyyy-MM-dd dddd"));
    }else{
        labelDate->clear();
    }
    this->setFixedSize(w,h);
}

void MainWindow::parseWeatherJsonData(QByteArray data)
{
    QJsonDocument doc=QJsonDocument::fromJson(data);
    if(!doc.isNull()&&doc.isObject()){
        QJsonObject jsonRoot=doc.object();
        QString tempStr=jsonRoot["tem"].toString();
        QString tem=jsonRoot["tem_night"].toString()+"~"+jsonRoot["tem_day"].toString();
        QString city=jsonRoot["city"].toString();
        QString str=city+"当日温度区间:"+tem;
        labelWeather->setText(str);
    }
}

void MainWindow::do_actSet_triggered()
{
    if(true){
        setTimeUIDialog=new SetTimeUIDialog(this);
        qDebug() << "Setting dialog created";
        setTimeUIDialog->setWindowFlag(Qt::WindowStaysOnTopHint);//设置窗口置顶

        setTimeUIDialog->setHour(isShow12H);
        setTimeUIDialog->setS(isShowS);
        setTimeUIDialog->setDate(isShowDate);
        setTimeUIDialog->setIcon(isShowIcon);
        setTimeUIDialog->setOpacity(opacityShow,opacityHide);
        setTimeUIDialog->showFont(labelTime->font());
        int ret=setTimeUIDialog->exec();
        if(ret==QDialog::Accepted){
            opacityShow=setTimeUIDialog->getOpacityShow();
            opacityHide=setTimeUIDialog->getOpacityHide();
            isShow12H=setTimeUIDialog->getIsShow12H();
            isShowS=setTimeUIDialog->getIsShowS();
            isShowDate=setTimeUIDialog->getIsShowDate();
            isShowIcon=setTimeUIDialog->getIsShowIcon();
            font=setTimeUIDialog->getFont();
            labelTime->setFont(font);
            labelDate->setFont(font);
        }
        qDebug() << "Setting dialog closed";
        delete setTimeUIDialog;
    }
}

void MainWindow::readHttpReply(QNetworkReply *reply)
{
    int resCode=reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
    qDebug()<<resCode;
    if(reply->error()==QNetworkReply::NoError&&resCode==200){
        //大多数服务器返回的是utf-8字符
        QByteArray data=reply->readAll();
        parseWeatherJsonData(data);
        qDebug()<<QString::fromUtf8(data);
    }else{
        QMessageBox mes;
        mes.setWindowTitle("错误");
        mes.setText("网络请求失败");
        mes.setStyleSheet("QPushButton {color:red}");
        mes.setStandardButtons(QMessageBox::Ok);
        mes.exec();
    }
}

void MainWindow::mousePressEvent(QMouseEvent *event)
{
    if(event->button()==Qt::RightButton){
        qDebug()<<"right Mouse clicked!";
        menu->exec(QCursor::pos());
    }
    if(event->button()==Qt::LeftButton){
        moving=true;
        this->setWindowOpacity(opacityShow);
        QPoint mouseGlobalPos=event->globalPosition().toPoint();
        dPosion=mouseGlobalPos-this->pos();
        qDebug()<<"mouset pos="<<event->globalPosition().toPoint();
        qDebug()<<"window pos="<<this->pos();
    }
}

void MainWindow::mouseMoveEvent(QMouseEvent *event)
{
    if(moving)
        this->move(event->globalPosition().toPoint()-dPosion);
}


void MainWindow::enterEvent(QEnterEvent *event)
{
    this->setWindowOpacity(opacityShow);
}

void MainWindow::leaveEvent(QEvent *event)
{
    if(!menuIsVisible){
        this->setWindowOpacity(opacityHide);
    }
}

void MainWindow::mouseReleaseEvent(QMouseEvent *event)
{
    moving=false;
}

